package com.tanhua.sso.service;

import com.tanhua.sso.pojo.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * 用户设置服务
 */
@Service
public class UsersService {

    @Autowired
    private SmsService smsService;
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public Boolean sendVerificationCode(String token) throws IOException {
        //查询到用户的手机号
        User user = this.userService.queryUserByToken(token);
        if (null == user) {
            return false;
        }
        String mobile = user.getMobile();
        this.smsService.sendCheckCode(mobile);
        return true;
    }

    public Boolean checkVerificationCode(String code, String token) throws IOException {
        //查询到用户的手机号
        User user = this.userService.queryUserByToken(token);
        if (null == user) {
            return false;
        }

        String redisKey = "CHECK_CODE_" + user.getMobile();
        String value = this.redisTemplate.opsForValue().get(redisKey);

        if (StringUtils.equals(value, code)) {
            //验证码正确
            this.redisTemplate.delete(redisKey);
            return true;
        }
        return false;
    }

    public Boolean updateNewMobile(String token, String newPhone) throws IOException {
        //查询到用户的手机号
        User user = this.userService.queryUserByToken(token);
        if (null == user) {
            return false;
        }
        return this.userService.updateNewMobile(user.getId(), newPhone);
    }
}
